import React, { useState } from "react";

interface ICreateFormOption<T={}> {
    defaultValues?: Partial<T>;
    name?: string;
}
export interface IFormRef<T={}> {
    formData: T;
}
interface ICreateFormResult<T={}> {
    useFormRef: () => IFormRef<T>;
}

export interface IFormContext {
    data: any;
    defaultValues: any;
    setData: (data: any) => void;
    set: (name: string, value: any) => void;
    reset: () => void;
}

export const FormContext = React.createContext({});

export const useForm = (): IFormContext => React.useContext(FormContext as any);

export const useFormRef = <T={}>(options?: ICreateFormOption<T>) => {
    const [ formRef ] = useState<any>({
        formObj: {
            defaultValues: options?.defaultValues
        }
    });
    return formRef.formObj;
};

export const createForm = <T={}>(options: ICreateFormOption<T>): ICreateFormResult<T> => {
    return {
        useFormRef: () => useFormRef(options)
    };
};